package com.xiaolong.common.context;

import java.io.Serial;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class ApplicationContext {
    private ApplicationContext(Map<String, Object> contextCache) {
        this.contextCache = contextCache;
    }

    private Map<String, Object> contextCache;

    private static ThreadLocal<ApplicationContext> threadLocal = new ThreadLocal<>();

    private final static String UserKey = "userKey";
    @Serial
    private static final long serialVersionUID = -1587480997064961371L;

    public static void init() {
        threadLocal.set(new ApplicationContext(new HashMap<>()));
    }

    public static void flush() {
        threadLocal.remove();
    }

    public static void put(String key, Object value) {
        threadLocal.get().putCache(key,value);
    }

    public static Object get(String key) {
        ApplicationContext applicationContext = threadLocal.get();
        if (Objects.isNull(applicationContext)){
            return null;
        }
        return applicationContext.getCache(key);
    }

    public static void putUser(UserInfo userInfo) {
        put(UserKey, userInfo);
    }

    public static UserInfo getUser() {
        return (UserInfo) get(UserKey);
    }


    private void putCache(String key, Object value) {
        contextCache.put(key, value);
    }

    private Object getCache(String key) {
        return contextCache.get(key);
    }

}
